package cn.cnsuh.controller.web.servlet;


import cn.cnsuh.domain.Ocr;
import cn.cnsuh.service.OcrService;
import cn.cnsuh.service.impl.OcrServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author Magic
 * @create 2020-05-23 22:35
 */
@WebServlet("/orcServlet")
public class OrcServlet extends HttpServlet {
    private OcrService ocrService = new OcrServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 设置阀值（默认吞吐量是10240byte：10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);

        // 设置临时文件存储的目录(仓库)
        String tmpPath = this.getServletContext().getRealPath("tmp");

        factory.setRepository(new File(tmpPath));

        // 创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        String msg = "";
//        ResultInfo ri = new ResultInfo();

        Ocr o = new Ocr();
        try {
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
//                System.out.println(fileItem.getContentType());
                if ("image/png".equals(fileItem.getContentType()) || "image/jpeg".equals(fileItem.getContentType()) && fileItem.getSize() < 1024 * 1024) {
                    String path = this.getServletContext().getRealPath("files");
                    ocrService.delAllFile(path);
                    String filePath = null;
                    if(fileItem.getName().endsWith(".jpg")){
                        filePath = path+ "/" + "aaa.jpg";
                    }else if (fileItem.getName().endsWith(".png")){
                        filePath = path+ "/" + "aaa.png";
                    }

//String filePath = this.getServletContext().getRealPath("files") + "\\" + fileItem.getName();
//                    System.out.println(filePath);//F:\java-workspace\idea-workspace\game_web\src\main\webapp\files\二分的步骤.png
                    fileItem.write(new File(filePath));
                    msg = ocrService.getRes(filePath);

                    o.setMsg(msg);
                    if(fileItem.getName().endsWith(".jpg")){
                        o.setImgPah("files/aaa.jpg");
                    }else if (fileItem.getName().endsWith(".png")){
                        o.setImgPah("files/aaa.png");
                    }
//                    o.setMsg(msg);
//                    o.setImgPah("files/"+fileItem.getName());

                } else {
                    fileItem.delete();
//                    msg = "请上传格式为jpg或png的图片且图片小于1M";
                    o.setMsg("请上传格式为jpg或png的图片且图片小于1M");
                    o.setImgPah("#");
                }
//                System.out.println(fileItem.getName());//注册功能页面.png  获取上传文件的文件名
//                System.out.println(fileItem.getContentType());//image/png 获取上传文件的文件类型
//                System.out.println(fileItem.getFieldName());/pic   获取组件/的name属性
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("o", o);
        request.getRequestDispatcher("/ocr.jsp").forward(request, response);
//        response.sendRedirect(request.getContextPath()+"/ocr.jsp");


        //响应数据
//        ObjectMapper mapper = new ObjectMapper();
//
//        response.setContentType("application/json;charset=utf-8");
//        mapper.writeValue(response.getOutputStream(), ri);
//        System.out.println(msg);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
